package com.express.conf.interceptor;

import com.express.aop.AuthToken;
import com.express.constants.Constants;
import com.express.entity.WxUser;
import com.express.service.IWxUserService;
import com.express.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


/**
 * @author zhoulin
 */
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Resource
    IWxUserService wxUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();
        // 获取请求信息
//        String token = request.getHeader("token"); //用户Token
//        String userMeta = request.getHeader("UserMeta");
//        String version = request.getHeader("Version");
//        String deviceCode = request.getHeader("DeviceCode"); // 获取设备编号
//        String ip = IPUtils.getIpAddr(request); //IP地址
//        String url = request.getRequestURL().toString();
        String authorization = request.getHeader("authorization");
//        log.debug("【IP地址: 】{}, 【用户Token: 】{}, 【版本号: 】{}, 【设备号: 】{},  【请求头部(来自平台及版本)信息: 】{},【请求URL地址:】{}", ip, token, version, deviceCode, userMeta, url);
        //方法过滤器，不拦截
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        WxUser userInfo = new WxUser();
        //普通请求，需要判断AuthToken
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //添加MDC日志
        // 生成唯一请求ID，并将其放入MDC上下文中
        String requestId = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put("requestId", requestId);
        MDC.put("beginTime",beginTime+"");
        AuthToken authToken = handlerMethod.getMethodAnnotation(AuthToken.class);
        // 不需要登录的请求直接通过
        if (null == authToken) {
            return true;
        }

        //校验是否携带token
        if (authToken.source() == 1) {
            // 管理平台用jwt 解析token
            //判断当前用户是否存在
            log.info("用户authorization：{}", authorization);
            if(StringUtils.isBlank(authorization)) {
                throw new RuntimeException("请求参数错误");
            }
            // 如是eEUDDH8NdlW7kW0ZaVJjHCkY7Die 就跳过
            if(authorization.equals(Constants.ENV_TOKEN)){
                return true;
            }
            userInfo = JwtUtil.verifyToken(authorization);
            if (null == userInfo) {
                throw new RuntimeException("登录已过期");
            }
            WxUser user = wxUserService.getUser(userInfo.getId(), userInfo.getOpenId());
            if (null == user) {
                throw new RuntimeException("登录已过期");
            }
            return true;
        }
        if(!ObjectUtils.anyNotNull(userInfo)){
            throw new RuntimeException("登录已过期");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //移除MDC日志
        MDC.remove("requestId");
        MDC.remove("beginTime");
    }
}
